import 'dart:io';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/domain/widgets/network_load_image.dart';
import 'package:flutter_syt/generated/assets.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/widgets/auto_image.dart';
import 'package:flutter_syt/widgets/loading_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'view_state_widget.dart';

const double kHeight = 90;

Widget commonRefreshStateWidget(String txt, Color color,
    {Color? textColor, String? path}) {
  return Container(
    alignment: Alignment.center,
    color: color,
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        AutoImage(
          path ?? Assets.refreshIcon,
          width: 30,
          height: 30,
        ),
        // Image.asset(
        //   path ?? ,
        //   width: 34,
        //   height: 30,
        //   // color: ,
        // ),
        Container(
          // color: Colors.red,
          padding: EdgeInsets.only(top: 8, bottom: 22),
          child: Text(
            txt,
            style: TextStyle(
              color:
                  textColor ?? Colors.black.withOpacity(0.4),
              fontSize: 14,
            ),
          ),
        ),
      ],
    ),
  );
}

Widget coloredRefreshHeader(Color color, String text,
    {String path = 'assets/icons/fresh_gray.png'}) {
  return Stack(
    children: [
      Container(
        height: 375,
        width: double.infinity,
        decoration: BoxDecoration(
          color: color,
        ),
      ),
      Positioned(
        left: 0,
        right: 0,
        bottom: 0,
        child: commonRefreshStateWidget(text, Colors.transparent,
            textColor: Colors.white, path: path),
      ),
    ],
  );
}

Widget coolRefreshHeader(String? imageUrl, String text) {
  if (imageUrl == null) {
    return commonRefreshStateWidget(
      text,
      Colors.transparent,
      textColor: Colors.white,
    );
  }
  return Stack(
    children: [
      Container(
        height: 375.w,
        width: double.infinity,
        decoration: BoxDecoration(
          color: Colors.white,
          // image: DecorationImage(
          //   fit: BoxFit.cover,
          //   image: CachedNetworkImageProvider(imageUrl),
          // ),
        ),
        child: NetworkLoadImage.loadNetworkImage(imageUrl,
            width: 375.w, height: 375.w),
      ),
      ClipRRect(
        child: BackdropFilter(
          filter: ImageFilter.blur(
            sigmaX: 20,
            sigmaY: 20,
          ),
          child: Container(
            height: 375,
            width: double.infinity,
          ),
        ),
      ),
      Positioned(
        left: 0,
        right: 0,
        bottom: 0,
        child: commonRefreshStateWidget(
          text,
          Colors.transparent,
          textColor: Colors.white,
        ),
      ),
    ],
  );
}

class NormalTableViewController {
  _SubCollectState? _inState;

  void refresh() {
    _inState?._scrollController.jumpTo(0);
    _inState?._controller.requestRefresh();
  }

  void animateTo(
    double offset, {
    Duration? duration,
    Curve? curve,
  }) {
    _inState?._scrollController.animateTo(0,
        duration: duration ?? Duration(milliseconds: 300),
        curve: curve ?? Curves.bounceInOut);
  }

  void reloadData() {
    _inState?._loadingGetData();
  }
}

int _defaultPageSize(page) => 15;

class NormalTableView<T> extends StatefulWidget {
  final Widget Function(BuildContext, T) itemBuilder; // 返回列表中每行Item
  final Widget Function(bool, String)? holder; // 空页面或者错误占位页面
  final EdgeInsets padding;
  final Future<List<T>> Function(int) getData; // 获取数据（接口函数）
  final int Function(int) pageSize; // 每页数据个数，默认15个
  final Widget Function(BuildContext)? header;
  final void Function(BuildContext context, double offset)? onScroll;

  // final Widget Function(BuildContext context, String text, RefreshStatus state)?
  //     refreshItemBuilder;
  final NormalTableViewController? controller;
  final bool enableRefresh;

  final bool enableLoadMore;
  final bool needAutoFreash;
  final Color? color;

  NormalTableView({
    required this.itemBuilder,
    this.holder,
    this.header,
    required this.getData,
    this.pageSize = _defaultPageSize,
    this.padding = EdgeInsets.zero,
    this.onScroll,
    this.controller,
    this.enableRefresh = true,
    this.enableLoadMore = true,
    this.needAutoFreash = true,
    this.color
    // this.refreshItemBuilder,
  });

  @override
  State<StatefulWidget> createState() {
    return _SubCollectState<T>();
  }
}

class _SubCollectState<T> extends State<NormalTableView<T>>
    with AutomaticKeepAliveClientMixin {
  final RefreshController _controller =
      RefreshController(initialRefresh: false);
  final ScrollController _scrollController = ScrollController();
  String? _error;
  List<T> _list = [];
  bool _firstLoading = true;
  int _page = 1;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    Future.delayed(const Duration(milliseconds: 200)).then((value) {
      if (widget.needAutoFreash) {
        _firstLoading = true;
        _loadingGetData();
      } else {
        _firstLoading = false;
      }
      setState(() {});
    });
    widget.controller?._inState = this;
    _scrollController.addListener(() {
      if (widget.onScroll != null) {
        widget.onScroll!(context, -_scrollController.position.pixels);
      }
    });
    super.initState();
  }

  @override
  dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  //第一次获取数据的时候，显示加载loading
  _loadingGetData() async {
    try {
      if (mounted) {
        setState(() {
          _firstLoading = true;
        });
      }
      await _firstGetData();
    } on DioError catch (e) {
      setState(() {
        if (e.error is SocketException) {
          _error = S.of(context).network_error;
        } else {
          _error = e.message;
        }
      });
    } catch (e, stack) {
      // _error = "$e";
      _error = S.of(context).network_error;
      debugPrintStack(stackTrace: stack);
    } finally {
      if (mounted) {
        setState(() {
          _firstLoading = false;
        });
      }
    }
  }

  _firstGetData() async {
    _page = 1;
    var array = await (widget as NormalTableView<T>).getData(1);
    if (array.length >= widget.pageSize(1)) {
      _controller.footerMode?.value = LoadStatus.idle;
    } else {
      _controller.footerMode?.value = LoadStatus.noMore;
    }
    if (mounted) {
      setState(() {
        _error = null;
        _list = array;
      });
    }
  }

  //下来获取数据
  void onRefresh() async {
    try {
      await _firstGetData();
      _controller.headerMode?.value = RefreshStatus.completed;
    } catch (e) {
      _controller.headerMode?.value = RefreshStatus.failed;
    }
  }

  //加载更多
  void onLoading() async {
    try {
      List<T> array = await widget.getData(_page + 1);
      _list += array;
      if (array.length >= widget.pageSize(_page + 1)) {
        _controller.footerMode?.value = LoadStatus.idle;
      } else {
        _controller.footerMode?.value = LoadStatus.noMore;
      }
      _page++;
      setState(() {});
    } catch (e) {
      _controller.footerMode?.value = LoadStatus.failed;
    }
  }

  Widget _showHolder() {
    if (_firstLoading) {
      return Container();
    }
    var child = widget.holder != null
        ? widget.holder!(_error != null, _error ?? "")
        : ViewStateEmptyWidget(
            message: _error != null ? "$_error" : null,
          );

    return TextButton(
      child: child,
      onPressed: ClickUtils.debounce(() {
        _loadingGetData();
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    Widget child = _showHolder();
    if (_firstLoading) {
      return LoadingWidget(
        color: widget.color,
      );
    } else if (_list.isNotEmpty || widget.header != null) {
      if (widget.header != null) {
        child = CustomScrollView(
          controller: _scrollController,
          slivers: [
            if (widget.header != null)
              SliverToBoxAdapter(
                child: widget.header!(context),
              ),
            SliverPadding(
              padding: widget.padding,
              sliver: SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    return widget.itemBuilder(context, _list[index]);
                  },
                  childCount: _list.length,
                ),
              ),
            )
          ],
        );
      } else {
        child = ListView.builder(
          padding: widget.padding,
          itemCount: _list.length,
          itemBuilder: (BuildContext context, int index) {
            return widget.itemBuilder(context, _list[index]);
          },
        );
      }
    } else if (_error != null) {
      return child;
    }
    return SmartRefresher(
      controller: _controller,
      onRefresh: onRefresh,
      onLoading: onLoading,
      enablePullUp: widget.enableLoadMore,
      enablePullDown: widget.enableRefresh,
      child: child,
    );
  }
}
